package cfs.model;

import org.mybeans.dao.DAOException;
import org.mybeans.dao.GenericDAO;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.MatchArg;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

import cfs.databean.Position;

public class PositionDAO extends GenericDAO<Position> {

	private BeanFactory<Position> factory;

	public PositionDAO(GenericDAO<?>[] referencedBeanDAOs) {
		super(Position.class, "Position", new String[] { "customer_id",
				"fund_id" }, referencedBeanDAOs);
		this.setIdleConnectionCleanup(true);

		BeanTable<Position> positionTable = getTable();
		positionTable.setIdleConnectionCleanup(true);
		factory = positionTable.getFactory();
	}

	public synchronized Position[] getPosition(int userId, int fundId)
			throws DAOException {
		try {
			System.out.println("Reached Position DAO");
			Position[] position = factory.match(MatchArg.and(
					MatchArg.equals("customer_id", userId),
					MatchArg.equals("fund_id", fundId)));
			return position;
		} catch (RollbackException e) {
			e.printStackTrace();
			throw new DAOException(e);
		}
	}

	public Position[] getFundsByCustomerId(int customer_id) throws DAOException {
		try {
			Position[] posList = this.getFactory().match(
					MatchArg.equals("customer_id", customer_id));
			return posList;
		} catch (RollbackException e) {
			throw new DAOException(e);

		}

	}

	public synchronized Position[] getFunds(int userId) throws DAOException {
		try {
			Position[] position = factory.match(MatchArg.equals("customer_id",
					userId));
			return position;
		} catch (RollbackException e) {
			e.printStackTrace();
			throw new DAOException(e);
		}
	}

	public long getAvailableShares(int customer_id, int fund_id)
			throws DAOException {
		try {
			Position p = factory.lookup(customer_id, fund_id);
			return p.getAvailableshares();
		} catch (RollbackException e) {
			throw new DAOException(e);
		}
	}

	public void updateAvailableShares(int customer_id, int fund_id,
			long newAvailableShares) throws DAOException {
		try {
			Transaction.begin();
			Position p = factory.lookup(customer_id, fund_id);
			p.setAvailableshares(newAvailableShares);
			Transaction.commit();
		} catch (RollbackException e) {
			throw new DAOException(e);
		} finally {
			if (Transaction.isActive())
				Transaction.rollback();
		}
	}

}
